package com.ruoyi.cems.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.base.domain.BaseEmerTeList;
import com.ruoyi.base.domain.BaseEmerTeTemp;
import com.ruoyi.base.service.IBaseEmerTeListService;
import com.ruoyi.base.service.IBaseEmerTeTempService;
import com.ruoyi.cems.domain.*;
import com.ruoyi.cems.mapper.BmsEVCContactMapper;
import com.ruoyi.cems.mapper.BmsEmergencyNoticeMapper;
import com.ruoyi.cems.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.domain.SearchCallResponse;
import com.ruoyi.common.domain.SendCallResponse;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TeamCallUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 应急通知Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-23
 */
@Slf4j
@Service
public class BmsEmergencyNoticeServiceImpl implements IBmsEmergencyNoticeService 
{
    @Autowired
    private BmsEmergencyNoticeMapper bmsEmergencyNoticeMapper;

    @Autowired
    private IBmsWorkChecklistsService bmsWorkChecklistsService;

    @Autowired
    private IBmsEmergencyVariableControlService evcService;

    @Autowired
    private IBaseEmerTeListService baseEmerTeListService;

    @Autowired
    private IBaseEmerTeTempService baseEmerTeTempService;

    @Autowired
    private IBmsWorkChecklistsDetailService workChecklistsDetailService;

    @Autowired
    private BmsEVCContactMapper bmsEVCContactMapper;

    @Autowired
    private TeamCallUtils teamCallUtils;

    @Autowired
    private IBmsUserMessageService bmsUserMessageService;

    @Autowired
    private ILanXinService iLanXinService;

    @Value("${call.TCL_Name}")
    private String tclName;

    @Value("${call.TCL_Content}")
    private String tclContent;

    @Value("${subscriber.messageEn}")
    private String messageEn;


    /**
     * 查询应急通知
     * 
     * @param ID 应急通知主键
     * @return 应急通知
     */
    @Override
    public BmsEmergencyNotice selectBmsEmergencyNoticeByID(String ID)
    {
        BmsEmergencyNotice notice = bmsEmergencyNoticeMapper.selectBmsEmergencyNoticeByID(ID);
        //获取应急通知下的应急检查单
        if (notice != null){
            notice.setBmsWorkChecklists(bmsWorkChecklistsService.selectBmsWorkChecklistsByEnID(ID));
        }
        return notice;
    }

    /**
     * 查询应急通知列表
     * 
     * @param bmsEmergencyNotice 应急通知
     * @return 应急通知
     */
    @Override
    public List<BmsEmergencyNotice> selectBmsEmergencyNoticeList(BmsEmergencyNotice bmsEmergencyNotice)
    {
        return bmsEmergencyNoticeMapper.selectBmsEmergencyNoticeList(bmsEmergencyNotice);
    }

    /**
     * 新增应急通知
     * 
     * @param bmsEmergencyNotice 应急通知
     * @return 结果
     */
    @Override
    public int insertBmsEmergencyNotice(BmsEmergencyNotice bmsEmergencyNotice)
    {
        //获取应急变量控制表上一次应急通知
        BmsEmergencyNotice noticeVo = new BmsEmergencyNotice();
        noticeVo.setVcId(bmsEmergencyNotice.getVcId());
        noticeVo.setManager(true);
        List<BmsEmergencyNotice> historyNoticeList = bmsEmergencyNoticeMapper.selectBmsEmergencyNoticeList(noticeVo);
        if (historyNoticeList != null && !historyNoticeList.isEmpty()){
            //关闭历史应急通知
            for (BmsEmergencyNotice historyNotice : historyNoticeList){
                close(historyNotice);
            }
        }
        //新增应急通知
        int result = bmsEmergencyNoticeMapper.insertBmsEmergencyNotice(bmsEmergencyNotice);
        if (result > 0) {
            //获取变量控制表关联的人员
            BmsEVCContact bevcc = new BmsEVCContact();
            bevcc.setParentId(bmsEmergencyNotice.getVcId());
            bevcc.setFlag(false);
            List<BmsEVCContact> list = bmsEVCContactMapper.getEVCContactListByparentId(bevcc);
            if (list != null && !list.isEmpty()) {
                for (BmsEVCContact bmsEVCContact : list) {
                    if (bmsEVCContact.getType().equals("command")) {
                        //当架次事故应急指挥部应急联络表:command
                        BmsWorkChecklists bmsWorkChecklists = new BmsWorkChecklists();
                        bmsWorkChecklists.setID(UUID.randomUUID().toString().replace("-", ""));
                        bmsWorkChecklists.setEnId(bmsEmergencyNotice.getID());
                        bmsWorkChecklists.setCreatedBy(bmsEmergencyNotice.getCreatedBy());
                        bmsWorkChecklists.setCreatedTime(bmsEmergencyNotice.getCreatedTime());
                        bmsWorkChecklists.setLevel(bmsEmergencyNotice.getResponseLevel());
                        bmsWorkChecklists.setView(bmsEmergencyNotice.getView());
                        bmsWorkChecklists.setTaskNo(bmsEmergencyNotice.getTaskForm());
                        bmsWorkChecklists.setCheckPeople(bmsEVCContact.getName());
                        bmsWorkChecklists.setCheckPeopleId(bmsEVCContact.getUserId());
                        bmsWorkChecklists.setPosition(bmsEVCContact.getPosition());
                        bmsWorkChecklists.setBelong(bmsEVCContact.getRole());
                        bmsWorkChecklists.setNoticeStatus(true);
                        bmsWorkChecklists.setJobNumber(bmsEVCContact.getJobNumber());
                        bmsWorkChecklists.setPhone(bmsEVCContact.getTel());
                        bmsWorkChecklists.setUnitCode(bmsEmergencyNotice.getUnitCode());
                        bmsWorkChecklists.setStatus("新建");

                        //获取检查单信息
                        BaseEmerTeList baseEmerTeList = baseEmerTeListService.selectBaseEmerTeListByViewAndPosition(bmsWorkChecklists.getView(), bmsWorkChecklists.getPosition(),bmsWorkChecklists.getUnitCode());
                        if (baseEmerTeList != null) {
                            bmsWorkChecklists.setCheckName(bmsEmergencyNotice.getTaskForm());
                            BaseEmerTeTemp bttemp = new BaseEmerTeTemp();
                            bttemp.setEmerTeId(baseEmerTeList.getID());
                            //生成检查单明细
                            List<BaseEmerTeTemp> baseEmerTeTemps = baseEmerTeTempService.selectBaseEmerTeTempList(bttemp);
                            if (baseEmerTeTemps != null && !baseEmerTeTemps.isEmpty()) {
                                for (BaseEmerTeTemp baseEmerTeTemp : baseEmerTeTemps) {
                                    BmsWorkChecklistsDetail bmsWorkChecklistsDetail = new BmsWorkChecklistsDetail();
                                    bmsWorkChecklistsDetail.setID(UUID.randomUUID().toString().replace("-", ""));
                                    bmsWorkChecklistsDetail.setCheckId(bmsWorkChecklists.getID());
                                    bmsWorkChecklistsDetail.setView(bmsEmergencyNotice.getView());
                                    bmsWorkChecklistsDetail.setInput(baseEmerTeTemp.getInput());
                                    bmsWorkChecklistsDetail.setOutput(baseEmerTeTemp.getOutput());
                                    bmsWorkChecklistsDetail.setResponseStage(baseEmerTeTemp.getResponseStage());
                                    bmsWorkChecklistsDetail.setCompletion("未完成");
                                    bmsWorkChecklistsDetail.setCreatedBy(bmsEmergencyNotice.getCreatedBy());
                                    bmsWorkChecklistsDetail.setCreatedTime(bmsEmergencyNotice.getCreatedTime());
                                    //新增检查单明细
                                    workChecklistsDetailService.insertBmsWorkChecklistsDetail(bmsWorkChecklistsDetail);
                                }
                            }
                        }
                        //新增检查单
                        bmsWorkChecklistsService.insertBmsWorkChecklists(bmsWorkChecklists);
                    }
                }
            }


            //更新S2 /B1  /B2对应的通知单号
            // 创建一个BmsWorkChecklists对象
            BmsWorkChecklists bwc = new BmsWorkChecklists();
            // 设置任务编号，关联到紧急通知的任务表单
            bwc.setTaskNo(bmsEmergencyNotice.getTaskForm());
            // 设置标志位为true，表示当前检查列表是有效的或需要特别处理
            bwc.setFlag(true);
            // 调用服务方法，查询符合当前条件的检查列表
            List<BmsWorkChecklists> bwcList = bmsWorkChecklistsService.selectBmsWorkChecklistsList(bwc);
            // 检查查询结果是否非空
            if (bwcList != null && !bwcList.isEmpty()) {
                // 遍历查询到的每一个检查列表项
                for (BmsWorkChecklists bwcl : bwcList) {
                    // 设置紧急通知的ID到检查列表项
                    bwcl.setEnId(bmsEmergencyNotice.getID());
                    // 设置场景
                    bwcl.setView(bmsEmergencyNotice.getView());
                    // 设置响应级别，同步紧急通知的响应级别到检查列表项
                    bwcl.setLevel(bmsEmergencyNotice.getResponseLevel());
                    // 更新检查列表项
                    bmsWorkChecklistsService.updateBmsWorkChecklists(bwcl);
                }
            }
        }
        return result;
    }

    private void userMessage(BmsEmergencyNotice bmsEmergencyNotice, String userId){
        BmsEVCContact bevcc = new BmsEVCContact();
        bevcc.setParentId(bmsEmergencyNotice.getVcId());
        List<BmsEVCContact> list = bmsEVCContactMapper.getEVCContactListByparentId(bevcc);
        if(Objects.nonNull(list) && !list.isEmpty()) {
            list.forEach(bmsEVCContact -> {
                //生成系统消息
                BmsUserMessage bmsUserMessage = new BmsUserMessage();
                bmsUserMessage.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsUserMessage.setEnId(bmsEmergencyNotice.getID());
                bmsUserMessage.setCreatedBy(userId);
                bmsUserMessage.setCreatedTime(new Date());
                bmsUserMessage.setUserId(bmsEVCContact.getUserId());
                bmsUserMessage.setType(2);
                bmsUserMessage.setMessage(messageEn.replace("v_cantry", bmsEmergencyNotice.getCantry()));
                bmsUserMessageService.insertBmsUserMessage(bmsUserMessage);
            });
        }
    }

    /**
     * 启动应急通知单
     * @param bmsEmergencyNotice
     * @return
     */
    @Override
    public AjaxResult start(BmsEmergencyNotice bmsEmergencyNotice ,String userId){
        //应急通知启动
        BmsEmergencyNotice dbBmsEmergencyNotice = bmsEmergencyNoticeMapper.selectBmsEmergencyNoticeByID(bmsEmergencyNotice.getID());
        int result = 0;
        if (dbBmsEmergencyNotice != null){
            dbBmsEmergencyNotice.setStatus("StartUp");
            dbBmsEmergencyNotice.setStartTime(new Date());
            //外呼人员名单
            JSONArray tcdlArray = new JSONArray();
            List<String> phoneList = new ArrayList<>();
            List<BmsWorkChecklists> bmsWorkChecklists = bmsEmergencyNotice.getBmsWorkChecklists();
            if (bmsWorkChecklists != null && !bmsWorkChecklists.isEmpty()){
                for (BmsWorkChecklists bmsWorkCheck : bmsWorkChecklists) {
                    if(bmsWorkCheck.getNoticeStatus()){
                        //外呼名单
                        JSONObject jsonObject = new JSONObject();
                        phoneList.add(bmsWorkCheck.getPhone());
                        jsonObject.put("TCDL_PhoneNum", bmsWorkCheck.getPhone());
                        jsonObject.put("TCDL_CustomerName", bmsWorkCheck.getCheckPeople());
                        // 检查是否已存在相同的记录
                        boolean isDuplicate = false;
                        for (Object obj : tcdlArray) {
                            JSONObject existingJson = (JSONObject) obj;
                            if (existingJson.getString("TCDL_PhoneNum").equals(jsonObject.getString("TCDL_PhoneNum"))) {
                                isDuplicate = true;
                                break;
                            }
                        }

                        if (!isDuplicate) {
                            tcdlArray.add(jsonObject);
                        }
                    }
                    BmsWorkChecklists dbBmsWorkChecklist = bmsWorkChecklistsService.selectBmsWorkChecklistsByID(bmsWorkCheck.getID());
                    if (dbBmsWorkChecklist != null){
                        dbBmsWorkChecklist.setNoticeStatus(bmsWorkCheck.getNoticeStatus());
                        bmsWorkChecklistsService.updateBmsWorkChecklists(dbBmsWorkChecklist);
                    }
                }
            }
            if (!tcdlArray.isEmpty()){
                String content = tclContent.replace("v_cantry", StringUtils.addSpacesToNumbers(dbBmsEmergencyNotice.getCantry()))
                        .replace("v_airport",StringUtils.addSpacesToNumbers(dbBmsEmergencyNotice.getAirport()));//替换通知内容参数
                System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@====="+content);
                //发起外呼
                SendCallResponse response = teamCallUtils.sendCall(tclName, content, tcdlArray.toJSONString());
                if (response != null){
                    if (response.getSuccess() == 1){
                        dbBmsEmergencyNotice.setCallSuccess(response.getSuccess());
                        dbBmsEmergencyNotice.setTclId(response.getTCL_ID());
                        dbBmsEmergencyNotice.setCallMsg(response.getMsg());
                    }else{
                        return AjaxResult.error("发起外呼失败，原因："+response.getMsg());
                    }
                }
                //发送蓝信消息通知
//                iLanXinService.sendTextMessage(phoneList, content);
                iLanXinService.sendLinkCardMessage(phoneList, "应急通知","https://comac-yjgl.e.lanxin.cn");
            }
            result = bmsEmergencyNoticeMapper.updateBmsEmergencyNotice(dbBmsEmergencyNotice);

            userMessage(dbBmsEmergencyNotice,userId);
        }
        return AjaxResult.success(result);
    }

    /**
     * 同步外呼结果
     */
    @Override
    public void syncCallResult(){
        //获取未同步外呼结果的通知单
        List<BmsEmergencyNotice> bmsEmergencyNotices = bmsEmergencyNoticeMapper.selectUnSyncBmsEmergencyNoticeList();
        if(bmsEmergencyNotices != null){
            log.info("获取到未同步外呼结果的通知单数：{}", bmsEmergencyNotices.size());
            bmsEmergencyNotices.forEach(bmsEmergencyNotice -> {
                log.info("开始同步通知单：{}", bmsEmergencyNotice.getNo());
                SearchCallResponse response = teamCallUtils.searchCall(bmsEmergencyNotice.getTclId());
                if (response != null){
                    //更新检查单外呼结果
                    if(response.getDetail() != null && !response.getDetail().isEmpty()){
                        response.getDetail().forEach(detail -> {
                            BmsWorkChecklists dbBmsWorkChecklists = new BmsWorkChecklists();
                            dbBmsWorkChecklists.setEnId(bmsEmergencyNotice.getID());
                            dbBmsWorkChecklists.setPhone(detail.getTCDL_PhoneNum());
                            List<BmsWorkChecklists> bmsWorkChecklists = bmsWorkChecklistsService.selectBmsWorkChecklistsList(dbBmsWorkChecklists);
                            if(bmsWorkChecklists != null && !bmsWorkChecklists.isEmpty()){
                                bmsWorkChecklists.forEach(bmsWorkCheck -> {
                                    //更新外呼状态
                                    if("呼叫成功".equals(detail.getTCDL_CallResult())){
                                        bmsWorkCheck.setCallStatus("已接听");
                                    }else {
                                        bmsWorkCheck.setCallStatus("未接听");
                                    }
                                    bmsWorkCheck.setTcdlCallTime(detail.getTCDL_CallTime());
                                    bmsWorkCheck.setTcdlAnswerTime(detail.getTCDL_AnswerTime());
                                    bmsWorkCheck.setTcdlHangupTime(detail.getTCDL_HangupTime());
                                    bmsWorkCheck.setTcdlCallCount(detail.getTCDL_CallCount());
                                    bmsWorkCheck.setTcdlCallResult(detail.getTCDL_CallResult());
                                    bmsWorkCheck.setTcdlCallState(detail.getTCDL_CallState());
                                    bmsWorkCheck.setTcdlSign(detail.getTCDL_Sign());
                                    bmsWorkCheck.setUpdatedTime(new Date());
                                    bmsWorkChecklistsService.updateBmsWorkChecklists(bmsWorkCheck);
                                });
                            }
                        });
                    }
                    //更新通知单外呼结果
                    bmsEmergencyNotice.setSearchSuccess(response.getSuccess());
                    bmsEmergencyNotice.setUpdatedTime(new Date());
                    bmsEmergencyNoticeMapper.updateBmsEmergencyNotice(bmsEmergencyNotice);
                }
            });
        }
    }

    /**
     * 关闭应急通知单
     * @param bmsEmergencyNotice
     * @return
     */
    @Override
    public int close(BmsEmergencyNotice bmsEmergencyNotice){
        //应急通知启动
        int result = 0;
        if (bmsEmergencyNotice != null){
            bmsEmergencyNotice.setStatus("Close");
            result = bmsEmergencyNoticeMapper.updateBmsEmergencyNotice(bmsEmergencyNotice);
        }
        //已经通知单状态更新为已结束，需要关闭下面所有检查单
        if (result > 0){
            bmsWorkChecklistsService.updateBmsWorkChecklistsByEnId(bmsEmergencyNotice.getID());
        }
        return result;
    }

    /**
     * 修改应急通知
     * 
     * @param bmsEmergencyNotice 应急通知
     * @return 结果
     */
    @Override
    public int updateBmsEmergencyNotice(BmsEmergencyNotice bmsEmergencyNotice)
    {
        return bmsEmergencyNoticeMapper.updateBmsEmergencyNotice(bmsEmergencyNotice);
    }

    /**
     * 批量删除应急通知
     * 
     * @param IDs 需要删除的应急通知主键
     * @return 结果
     */
    @Override
    public int deleteBmsEmergencyNoticeByIDs(String[] IDs)
    {
        //删除应急单对应的检查单
        return bmsEmergencyNoticeMapper.deleteBmsEmergencyNoticeByIDs(IDs);
    }

    /**
     * 删除应急通知信息
     * 
     * @param ID 应急通知主键
     * @return 结果
     */
    @Override
    public int deleteBmsEmergencyNoticeByID(String ID)
    {
        return bmsEmergencyNoticeMapper.deleteBmsEmergencyNoticeByID(ID);
    }

    /**
     * 查询业务数据数量
     *
     * @param start_time
     * @param end_time
     * @return
     */
    @Override
    public int selectBmsEmergencyNotice(String start_time, String end_time) {
        int data_num = bmsEmergencyNoticeMapper.selectBmsEmergencyNoticeCount(start_time, end_time);
        return data_num;
    }

    /**
     * 更新应急通知状态
     */
    @Override
    public int updateBmsEmergencyNoticeStatus() {
        return bmsEmergencyNoticeMapper.updateBmsEmergencyNoticeStatus();
    }

}
